<?php

 
// no direct access
defined('_JEXEC') or die('Restricted access');

class HelpDeskModelUsers extends HelpDeskModel 
{
	/**
	 * constructor
	 * @return array Array of objects containing the data from the database
	 */	
	function __construct() 
	{
		parent::__construct();
	}
	
	/**
	 * Returns the query
	 * @return string The query to be used to retrieve the rows from the database
	 */
	function _buildQuery() 
	{
		$database = HelpDeskConfig::getDBO();
		$config = HelpDeskConfig::getInstance();
		$where = array();
		
		// search
			$search = $this->getField( $config->getFieldName( 'search' ) );
			if (isset($search)) {
					$where[] = " LOWER(s.id) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
					$where[] = " LOWER(s.name) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
					$where[] = " LOWER(s.username) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
					$where[] = " LOWER(s.email) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
			}
			$where_query = count( $where ) ? "\n HAVING " . implode( ' OR ', $where ) : "";
	
		// order
			$order_query = "";
			$this->_order 	= $this->getOrder();
			$this->_order_dir = $this->getOrderDir();
			switch ($this->_order) {
				case "id":
					$order_query = " ORDER BY s.id ".strtoupper( $this->_order_dir )." ";
				  break;
				case "name":
					$order_query = " ORDER BY s.name ".strtoupper( $this->_order_dir )." ";
				  break;
				case "username":
					$order_query = " ORDER BY s.username ".strtoupper( $this->_order_dir )." ";
				  break;
				case "email":
					$order_query = " ORDER BY s.email ".strtoupper( $this->_order_dir )." ";
				  break;
				default:
					$order_query = " ORDER BY s.id ASC ";
				  break;
			}
				
		// query
			$query = "
				SELECT 
					s.* 
				FROM 
					#__users as s
				WHERE 1
					{$where_query}
					{$order_query}
			";
			
		return $query;
	}		
}